﻿@page "/fetchdataapi"
@attribute [Authorize]

<PageTitle>Weather forecast</PageTitle>

@using BlzOidc.Data
@inject WeatherForecastApiClient ForecastService
@inject NavigationManager navManager

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (!string.IsNullOrWhiteSpace(err))
{
    <div class="text-danger m-4">@err</div>
}

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[]? forecasts;

    private string err = "";

    protected override async Task OnInitializedAsync()
    {
        err = "";

        try
        {
            forecasts = await ForecastService.GetForecastAsync();
        }
        catch (Exception ex)
        {
            err = ex.Message;
            if ((ex is HttpRequestException requestException) && (requestException.StatusCode == System.Net.HttpStatusCode.Unauthorized))
            {
                //如果token过期，自动跳转登录
                //如果cookies登录状态有效，自动登录成功，自动跳转回到当前页面
                navManager.NavigateTo($"account/login?returnUrl={Uri.EscapeDataString(navManager.Uri)}", true);
            }
        }
    }
}
